package cn.jinjimi.app.main.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import bolts.Continuation;
import bolts.Task;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.AccountController;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.LoginEvent;
import cn.jinjimi.app.main.activity.LoginActivity;
import cn.jinjimi.app.main.dialog.VerifyCodeDialog;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.MTextWatcher;
import cn.jinjimi.app.main.widget.PhoneBaseEditTextView;
import cn.jinjimi.app.util.ToastUtil;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.domain.data.dto.TokenDto;

/**
 *
 * @author HANER
 * @date 15/4/12
 */
public class LoginFragment extends BaseFragment implements View.OnClickListener, View.OnFocusChangeListener {
    private LinearLayout llContainer;
    private ImageView ivLogo;
    private EditText valid;
    private TextView mGetValidCodeButton;
    private TextView mSignInButton;
    private Button mCleanValidCode;
    private PhoneBaseEditTextView phone;
    private Button cleanPhone;
    private String openId;
    private String unionId;
    private VerifyCodeDialog mDialog;
    private TextView mLoginByPwd;
    private long mSendTime;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {

        getActivity().setTitle(R.string.title_phone_login);

        llContainer = (LinearLayout) findView().findViewById(R.id.ll_login_container);
        ivLogo = (ImageView) findView().findViewById(R.id.iv_logo);
        phone = (PhoneBaseEditTextView) findView().findViewById(R.id.et_phone);
        cleanPhone = (Button) findView().findViewById(R.id.bt_clean_phone_number);
        mSignInButton = findView().findViewById(R.id.bt_sign_in);
        valid = (EditText) findView().findViewById(R.id.valid_code);
        mGetValidCodeButton = findView().findViewById(R.id.get_valid_code);
        mCleanValidCode = (Button) findView().findViewById(R.id.clean_valid_code);
        mLoginByPwd = (TextView) findView().findViewById(R.id.login_by_pwd);

        llContainer.setFocusable(true);
        llContainer.setFocusableInTouchMode(true);
        llContainer.requestFocus();
        cleanPhone.setVisibility(StringUtils.isEmpty(phone.getText().toString()) ? View.GONE : View.VISIBLE);
    }

    protected void initListener() {
        llContainer.setOnClickListener(this);
        cleanPhone.setOnClickListener(this);
        mCleanValidCode.setOnClickListener(this);
        mGetValidCodeButton.setOnClickListener(this);
        mSignInButton.setOnClickListener(this);
        phone.addTextChangedListener(new MTextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 手机号框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanPhone.setVisibility(View.VISIBLE);
                } else {
                    cleanPhone.setVisibility(View.INVISIBLE);
                }
            }
        });
        valid.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 验证码框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    mCleanValidCode.setVisibility(View.VISIBLE);
                } else {
                    mCleanValidCode.setVisibility(View.INVISIBLE);
                }
            }
        });
        llContainer.setOnFocusChangeListener(this);
        phone.setOnFocusChangeListener(this);
        valid.setOnFocusChangeListener(this);
        mLoginByPwd.setOnClickListener(this);
    }

    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_login_container:
                phone.clearFocus();
                valid.clearFocus();
            case R.id.clean_valid_code:
                valid.setText("");
                break;

            case R.id.bt_clean_phone_number:
                phone.setText("");
                break;

            case R.id.get_valid_code:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    getVerifyCaptcha(phone.getRealPhoneNum());
                }
                break;
            case R.id.bt_sign_in:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    if (StringUtils.checkValidCode(getActivity(), valid)) {
                        handlerLogin();
                    }
                }
                break;
            case R.id.login_by_pwd:
                toLoginByPwd();
                break;
            default:break;
        }
    }

    private void toLoginByPwd() {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.setTransitionStyle(R.style.window_in_out_anim_style);
        ft.replace(R.id.content_fragment, new LoginWithPswFragment());
        ft.addToBackStack(null);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_phone:
            case R.id.valid_code:
                ivLogo.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
                break;
            case R.id.ll_login_container:
                if (hasFocus) {
                    InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            default:break;
        }
    }

    /**
     *  登录
     */
    private void handlerLogin() {
        if (checkActivityExit()) {
            return;
        }

        String mobile = phone.getRealPhoneNum().trim();
        String captcha = valid.getText().toString().trim();
        sendVerifyAndLogin(mobile, captcha);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        if (!isVisible()) {
            return;
        }

        switch (event.state) {
            case DataEvent.SUCC:
                break;
            case DataEvent.FAIL:
                break;
            default:break;
        }

        ((LoginActivity) getActivity()).hideLoadingIndicator();
    }

    /**
     * 获取验证码
     *
     */
    private void getVerifyCaptcha(String mobile) {
        valid.requestFocus();
        // 防止60内重复发送请求
        if (mSendTime + 60 * 1000 > System.currentTimeMillis()) {
            ToastUtil.showCusToast(getActivity(), getResources().getString(R.string.account_send_captcha));
            return;
        }

        mGetValidCodeButton.setEnabled(false);
        AccountController
                .getCaptcha(mobile)
                .onSuccess(new Continuation<Boolean, Void>() {
                    @Override
                    public Void then(Task<Boolean> task) throws Exception {
                        if (task.getResult()) {
                            mSendTime = System.currentTimeMillis();
                            ToastUtil.showCusToast(getActivity(), getResources().getString(R.string.account_send_captcha));
                        } else {
                            mSendTime = 0;
                            ToastUtil.showCusToast(getActivity(), getResources().getString(R.string.account_send_captcha_err));
                        }
                        mGetValidCodeButton.setEnabled(true);
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    /**
     * 短信验证码登陆
     *
     * @param captcha
     */
    private void sendVerifyAndLogin(final String mobile, final String captcha) {

        ((LoginActivity) getActivity()).showLoadingIndicator();

        UserController
                .login(mobile, captcha)
                .continueWith(new Continuation<TokenDto, Void>() {
                    @Override
                    public Void then(Task<TokenDto> task) throws Exception {
                        ((LoginActivity) getActivity()).hideLoadingIndicator();
                        if (task.isCompleted()) {
                            TokenDto dto = task.getResult();
                            if (dto == null || dto.code == Constants.Code.CODE_USER_NOT_FOUND) {
                                onFirstLogin(mobile, captcha);
                            }
                            if (dto != null && TextUtils.isEmpty(dto.token)) {
                                ToastUtil.showCusToast(getActivity(), dto.message);
                            }
                            onLoginComplete();
                        }
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    private void onLoginComplete() {
        phone.savePhoneNum();
    }

    private void onFirstLogin(String mobile, String captcha) {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.content_fragment,
                RegisterPswFragment.newInstance(mobile, captcha),
                null);
        ft.addToBackStack(null);
        ft.commit();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        AndroidUtils.hideSoftKeyBoard(getActivity(), phone);
    }

    @Override
    public void onDestroyView() {
        if (mDialog != null) {
            mDialog.dismissDialog();
            mDialog = null;
        }
        super.onDestroyView();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
